package com.kaohe.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.kaohe.domain.Category;
import com.kaohe.domain.Product;
import com.kaohe.utils.C3P0Utils;

public class ProductDao {

	//总记录数
	public int Pcount() {
		Long lo=0L;
		QueryRunner qr=new QueryRunner(C3P0Utils.getDataSource());
		String sql="select count(*) from product";
		try {
			lo = (Long) qr.query(sql, new ScalarHandler());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return lo.intValue();
	}

	//当前页信息
	public List<Product> pqueery(int startIndex, int pageSize) {
		List<Product>result=null;
		QueryRunner qr=new QueryRunner(C3P0Utils.getDataSource());
		String sql="select *from product limit ?,?";
		Object[]param={startIndex,pageSize};
		try {
			result = qr.query(sql, param, new BeanListHandler<>(Product.class));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return result;
	}

	//添加
		public void addproduct(Product product) {
			try {
				QueryRunner qr=new QueryRunner(C3P0Utils.getDataSource());
				String sql="insert into product values(?,?,?,?,?,?,?,?,?,?)";
				Object[] params = {null,product.getPname(),product.getColor(),product.getPrice(),
						product.getDescription(),product.getPic(),product.getState(),product.getVersion(),
						product.getProduct_date(),product.getCid()};
				qr.update(sql, params);
			} catch (SQLException e) {
				e.printStackTrace();
			}

		}

	//修改-跳转页面
	public Product toUpdateproduct(String pid) {
		Product product=null;
		QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
		String sql = "select *from product where pid=?";
				try {
			product = qr.query(sql, pid, new BeanHandler<>(Product.class));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return product;
		
	}
	//修改-修改数据
	public void update(Product product) {
		try {
			QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
			String sql="update product set cid=?, pname=?,color=?,price=?,description=?,pic=?,state=?,version=?,product_date=? where pid=?";
			Object[] params={product.getCid(),product.getPname(),product.getColor(),product.getPrice(),product.getDescription(),product.getPic(),product.getState(),product.getVersion(),product.getProduct_date(),product.getPid()};
			qr.update(sql, params);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	
	}
	//删除
		public void deProduct(String pid) {
			try {
				QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
				String sql="delete from product where pid=?";
				qr.update(sql, pid);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
	
}
